package utils

import (
	"errors"
	"os"
	"sync"
	"time"

	"github.com/golang-jwt/jwt/v5"
	"golang.org/x/crypto/bcrypt"
)

type Claims struct {
	jwt.RegisteredClaims
	Username string `json:"username"`
	ID       uint   `json:"id"`
}

var blacklistedTokens = struct {
	sync.RWMutex
	tokens map[string]struct{}
}{tokens: make(map[string]struct{})}

var jwtKey = os.Getenv("JWT_KEY")

// 生成token
func GenerateToken(id uint, username string) string {
	var claims Claims
	claims.ID = id
	claims.Username = username
	claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Hour * 72))
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, _ := token.SignedString([]byte(jwtKey))
	return tokenString
}

// token添加到黑名单
func InvalidateToken(tokenString string) {
	blacklistedTokens.Lock()
	defer blacklistedTokens.Unlock()
	blacklistedTokens.tokens[tokenString] = struct{}{}
}

// 检查是否在黑名单中
func isTokenBlacklisted(tokenString string) bool {
	blacklistedTokens.RLock()
	defer blacklistedTokens.RUnlock()
	_, exists := blacklistedTokens.tokens[tokenString]
	return exists
}

// 验证token
func ValidateToken(tokenString string) (*Claims, error) {
	if isTokenBlacklisted(tokenString) {
		return nil, errors.New("token is blacklisted")
	}
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return []byte(jwtKey), nil
	})
	if err != nil || token == nil || !token.Valid || claims.Username == "" {
		return nil, err
	}
	return claims, nil
}

// 密码加密
func HashPassword(password string) (string, error) {
	bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	return string(bytes), err
}

// 密码验证
func CheckPasswordHash(password, hash string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
	return err == nil
}
